<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="70%" :title="drawerTitle">
    <div class="drawer-content">
      <el-form :model="formData" label-width="80px" ref="formRef">
        <el-form-item label="文档标题" prop="name">
          <el-input v-model="formData.name" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="文档内容" prop="content">
          <WangEditor v-model:value="formData.content" :height="'100%'" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="DocEditDrawer">
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";
import { ShareDoc } from "./types/document";
import apiService from "@/api/services/apiService";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();

const loading = ref(false);
const formRef = ref();

interface DrawerProps {
  row: Partial<ShareDoc>;
  api?: (tabName: string, params: any) => Promise<any>;
  updateCurShareDoc?: (content: string | undefined) => void;
  refreshTreeItem?: (updatedDoc: ShareDoc) => void; // 添加更新树中特定项的方法
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  row: {}
});

// 表单数据
const formData = reactive({
  _id: "",
  name: "",
  content: ""
});

// 动态计算抽屉标题
const drawerTitle = computed(() => {
  return formData.name ? `编辑文档 - ${formData.name}` : "编辑文档";
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  formData._id = params.row._id || "";
  formData.name = params.row.name || "";
  formData.content = params.row.content || "";
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 比较两个字符串内容是否相同（去除空白字符差异）
const isContentEqual = (content1: string, content2: string): boolean => {
  // 去除首尾空白字符并标准化内部空白字符
  const normalize = (str: string) => {
    return str?.trim().replace(/\s+/g, " ") || "";
  };
  return normalize(content1) === normalize(content2);
};

// 生成内容变化的备注信息
const generateChangeNote = (oldContent: string, newContent: string): string => {
  // 去除首尾空白字符并标准化内部空白字符
  const normalize = (str: string) => {
    return str?.trim().replace(/\s+/g, " ") || "";
  };

  const normalizedOld = normalize(oldContent);
  const normalizedNew = normalize(newContent);

  // 如果内容相同，返回默认备注
  if (normalizedOld === normalizedNew) {
    return "无内容变化";
  }

  // 简单的差异分析
  if (normalizedOld === "" && normalizedNew !== "") {
    return "新增内容";
  }

  if (normalizedOld !== "" && normalizedNew === "") {
    return "删除所有内容";
  }

  // 计算字符变化
  const oldLength = normalizedOld.length;
  const newLength = normalizedNew.length;
  const diff = newLength - oldLength;

  if (diff > 0) {
    return `内容增加${diff}个字符`;
  } else if (diff < 0) {
    return `内容减少${Math.abs(diff)}个字符`;
  } else {
    return "内容有修改";
  }
};

// 提交数据（新增/编辑）
const handleSubmit = async () => {
  if (!formData.name) {
    ElMessage.warning("请输入文档标题");
    return;
  }

  if (!formData._id) {
    ElMessage.warning("文档信息不完整");
    return;
  }

  loading.value = true;
  try {
    // 更新文档
    const updatedDoc = {
      _id: formData._id,
      name: formData.name,
      content: formData.content,
      lastModifyDate: new Date()
    };
    await apiService.updateById("shareDoc", updatedDoc);

    // 只有在内容发生变化时才保存版本历史
    if (!isContentEqual(formData.content, drawerProps.value.row.content || "")) {
      // 生成变化备注
      const changeNote = generateChangeNote(drawerProps.value.row.content || "", formData.content);

      // 保存版本历史
      const versionData = {
        catalogId: formData._id,
        version: generateVersionNumber(),
        content: formData.content,
        note: changeNote,
        createDate: new Date(),
        createUser: userStore.userInfo._id || "" // 使用当前用户ID
      };
      await apiService.save("shareDocVersions", versionData);
    }

    // 更新父组件的文档内容
    if (drawerProps.value.updateCurShareDoc) {
      drawerProps.value.updateCurShareDoc(formData.content);
    }

    // 只更新修改的那条记录，而不是整个刷新树
    if (drawerProps.value.refreshTreeItem) {
      drawerProps.value.refreshTreeItem({
        ...updatedDoc,
        id: formData._id,
        viewCount: drawerProps.value.row?.viewCount || 0,
        likeCount: drawerProps.value.row?.likeCount || 0,
        children: drawerProps.value.row?.children || []
      } as ShareDoc);
    }

    ElMessage.success({ message: "保存成功！" });
    drawerVisible.value = false;
  } catch (error) {
    console.error("保存文档失败:", error);
    ElMessage.error({ message: "保存失败！" });
  } finally {
    loading.value = false;
  }
};

defineExpose({
  acceptParams
});

// 生成有意义的版本号
const generateVersionNumber = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  // 格式：YYYYMMDD.HHMMSS
  return `${year}${month}${day}.${hours}${minutes}${seconds}`;
};
</script>

<style scoped lang="scss">
.drawer-content {
  height: calc(100% - 40px);
  :deep(.el-form) {
    display: flex;
    flex-direction: column;
    height: 100%;
    .el-form-item {
      &:nth-child(2) {
        // 文档内容表单项
        display: flex;
        flex: 1;
        flex-direction: column;
        overflow: hidden;
        :deep(.el-form-item__content) {
          display: flex;
          flex: 1;
          flex-direction: column;
          overflow: hidden;
          .wangeditor-container {
            flex: 1;
            overflow: hidden;
          }
        }
      }
    }
  }
}
</style>
